import type { useVbenDrawer, VbenFormProps } from '@vben/common-ui'
import { useVbenModal } from '@vben/common-ui'
import type { VxeGridProps } from '@vben/plugins/vxe-table'
import { isUndefined } from '@vben/utils'

import { useVbenVxeGrid } from '#/adapter/vxe-table'

import { computed, unref } from 'vue'
import type {
    BaseFormComponentType,
    FormSchema
} from '../../../../packages/@core/ui-kit/form-ui/src/types'
import { usePageCURD } from './usePageCURD'

/**
 * 表格列表
 */
export function useTableList(opts: {
    /**
     * 单元格最小宽度
     */
    cellMinWidth?: number | string
    formOptions?: VbenFormProps
    gridEvents?: Parameters<typeof useVbenVxeGrid>[0]['gridEvents']
    gridOptions: VxeGridProps
    /**
     * 是否隐藏表单搜索
     */
    isHideForm?: boolean
}) {
    const {
        formOptions: _formOptions,
        gridOptions: _gridOptions,
        cellMinWidth = 80,
        gridEvents,
        isHideForm
    } = opts

    const formOptions: VbenFormProps = {
        // 控制表单是否显示折叠按钮
        showCollapseButton: false,
        // 按下回车时是否提交表单
        submitOnEnter: true,
        wrapperClass: 'flex-important flex-wrap',
        actionWrapperClass: 'w-auto',
        ..._formOptions,
        schema: computed(() => {
            return unref(_formOptions?.schema || []).map((v) => {
                const obj = v as any

                if (obj.component === 'Select') {
                    obj.componentProps = {
                        ...obj.componentProps,
                        style: {
                            minWidth: '180px',
                            ...obj?.componentProps?.style
                        }
                    }
                }
                return obj as FormSchema<BaseFormComponentType>
            })
        })
    }

    const gridOptions: VxeGridProps<any> = {
        showOverflow: true,
        data: [],
        ..._gridOptions,
        columns: _gridOptions.columns?.map((item) => {
            const obj = item
            // 防止过小
            if (isUndefined(obj.minWidth) && isUndefined(obj.width)) {
                obj.minWidth = cellMinWidth
            }
            return obj
        }),
        toolbarConfig: {
            custom: true,
            // import: true,
            refresh: true,
            zoom: true,
            ..._gridOptions?.toolbarConfig
        }
    }

    const [Grid, GridApi] = useVbenVxeGrid({
        formOptions: isHideForm ? undefined : formOptions,
        gridOptions,
        gridEvents
    })

    function reload() {
        GridApi?.reload()
    }

    // 获取选中的行
    function getSelectRows(isFull = true) {
        const grid = GridApi?.grid
        if (grid && Object.keys(grid).length > 0) {
            return gridOptions?.checkboxConfig?.reserve
                ? [...grid.getCheckboxRecords(isFull), ...grid.getCheckboxReserveRecords(isFull)]
                : grid.getCheckboxRecords(isFull)
        }

        return []
    }

    function clearSelectedRowKeys() {
        GridApi?.grid?.clearCheckboxRow()
        GridApi?.grid?.clearCheckboxReserve()
    }

    return { Grid, GridApi, reload, getSelectRows, clearSelectedRowKeys }
}

/**
 * 增删改查
 */
export function useTableCURD<TableListItem extends Record<string, any>>(opts: {
    beforeDelParams?: (...args: any[]) => any | Promise<any>
    /**
     * 单元格最小宽度
     */
    cellMinWidth?: number | string
    delApi?: (...args: any[]) => Promise<any>
    formOptions?: VbenFormProps
    gridEvents?: Parameters<typeof useVbenVxeGrid>[0]['gridEvents']
    gridOptions: VxeGridProps<any>
    idKey?: string
    /**
     * 是否隐藏表单搜索
     */
    isHideForm?: boolean
    modalOptions?: Parameters<typeof useVbenDrawer>[0] & Parameters<typeof useVbenModal>[0]
    modalType?: 'drawer' | 'modal'
    onReload?: (...args: any[]) => void
    statusKey?: string
    updateStatusApi?: (...args: any[]) => Promise<any>
}) {
    const {
        delApi,
        idKey = 'id',
        statusKey = 'status',
        updateStatusApi,
        modalOptions,
        formOptions,
        gridOptions,
        isHideForm,
        beforeDelParams,
        modalType,
        gridEvents,
        onReload
    } = opts

    const { Grid, GridApi, reload, getSelectRows, clearSelectedRowKeys } = useTableList({
        formOptions,
        gridOptions,
        isHideForm,
        gridEvents
    })

    const { FormModal, formModalApi, add, edit, viewDetail, updateStatus, del, delBatch } =
        usePageCURD<TableListItem>({
            beforeDelParams,
            delApi,
            getSelectRows,
            idKey,
            modalOptions,
            onSuccess() {
                handleSuccess()
            },
            statusKey,
            updateStatusApi,
            async updateStatusSuccess(record, status) {
                return await GridApi?.grid.setRow(record, { [statusKey]: status })
            },
            modalType
        })

    function handleSuccess() {
        reload()
        onReload?.()
    }

    return {
        reload,
        getSelectRows,
        clearSelectedRowKeys,
        add,
        edit,
        del,
        viewDetail,
        updateStatus,
        FormModal,
        formModalApi,
        GridApi,
        Grid,
        handleSuccess,
        delBatch,
        modalType
    }
}
